/**   
 * @Title: ArchiveclassmanagerServiceImpl.java 
 * @Package avicit.im.lantop.basic.archiveclassmanager.service.impl 
 * @Description: fixme(用一句话描述该文件做什么) 
 * @author A18ccms A18ccms_gmail_com   
 * @date 2014-9-23 下午1:50:05 
 * @version V1.0   
 */
package avicit.im.lantop.basic.archiveclassmanager.action.service.impl;

import avicit.cbb.tabledefine.service.CommTableManagerIntfsService;
import avicit.im.lantop.basic.archiveclassmanager.action.service.UserAuthIntfsService;
import avicit.im.lantop.basic.archiveclassmanager.domain.LantopArchiveClass;
import avicit.im.lantop.basic.archiveclassmanager.service.ArchiveclassmanagerService;
import avicit.im.lantop.userauthset.service.UserAuthIntfsService;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.Pinyin4jUtil;
import avicit.platform6.commons.utils.PojoUtil;
import avicit.platform6.commons.utils.web.TreeNode;
import avicit.platform6.core.dao.Paging;
import avicit.platform6.core.domain.BeanBase;
import avicit.platform6.core.exception.DaoException;
import avicit.platform6.core.jdbc.JdbcAvicit;
import avicit.platform6.core.properties.PlatformConstant.OpResult;
import avicit.platform6.core.properties.PlatformConstant.OpType;
import avicit.platform6.core.service.ServiceBase;
import avicit.platform6.modules.system.syslog.service.LogBaseFactory;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>金航数码科技有限责任公司</p>
 * <p>作者：钟一华</p>
 * <p>邮箱：feifan1985@163.com</p>
 * <p>创建时间： 2014-9-24 上午8:39:35 </p>
 * <p>类说明：archiveclassmanager模块service</p>
 * <p>修改记录： </p>
 */
@Service
@SuppressWarnings({"unchecked", "deprecation"})
public class ArchiveclassmanagerServiceImpl extends ServiceBase implements ArchiveclassmanagerService {

	@Resource
	JdbcAvicit jdbcAvicit;

	@Autowired(required = true)
	private CommTableManagerIntfsService commTableManagerIntfsService;

	@Resource
	private UserAuthIntfsService userAuthIntfsService;

	@Override
	public void delete(BeanBase arg0) throws DaoException {
		// TODO Auto-generated method stub

	}

	@Override
	public void insert(BeanBase arg0) throws DaoException {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(BeanBase arg0) throws DaoException {
		// TODO Auto-generated method stub

	}

	/**
	 * 递归获取tree当前节点下数据
	 * @author 钟一华
	 * @param id 当前节点
	 * @return List<TreeNode> 节点集合
	 * @throws
	 */
	public List<TreeNode> recurFindTreeNodesByParentId(String id, String orgId, String deptId, int level) throws Exception {
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		if (level == 0) {
			return null;
		}
	    level--;
		try {
			// 查询业务数据
			List<Map<String, Object>> childTreeList = findNodesByParentId(id, orgId, deptId);
			// 将业务数据格式转换成esayui树形格式，此处封装了一个TreeNodeVo节点
			for (Map<String, Object> row : childTreeList) {
				System.out.println((String) row.get("archive_class_node_name"));
				String rid = (String) row.get("id");
				String rname = (String) row.get("archive_class_node_name");
				String archiveType = (String) row.get("ARCHIVE_TYPE");
				String nodeType = (String) row.get("ARCHIVE_CLASS_NODE_TYPE");
				String parentId = (String) row.get("PARENT_ID");
				TreeNode node = new TreeNode();
				node.setId(rid);
				node.setText(rname);
				// 根据节点类型,设置节点图标
				if (null != parentId && "ROOT".equals(parentId)) { // 根节点
					node.setIconCls("icon-im-newnorg");
				} else if (null != archiveType && "-1".equals(archiveType) && null == nodeType) { // 档案类型 -1 物理表
					node.setIconCls("icon-im-newntable");
				} else if (null != archiveType && "0".equals(archiveType) && null == nodeType) { // 0 模版文件夹
					node.setIconCls("icon-im-newnmodulefile");
				} else if (null != archiveType && "1".equals(archiveType) && null == nodeType) { // 1 标识文件
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "2".equals(archiveType) && null == nodeType) { // 2 档案
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "3".equals(archiveType) && null == nodeType) { // 3 专题库
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "4".equals(archiveType) && null == nodeType) { // 4 多媒体
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "5".equals(archiveType) && null == nodeType) { // 5 项目归档计划
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "6".equals(archiveType) && null == nodeType) { // 6 管务
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "7".equals(archiveType) && null == nodeType) { // 7 其他
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "8".equals(archiveType) && null == nodeType) { // 8 资料
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "9".equals(archiveType) && null == nodeType) { // 9 图书
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "10".equals(archiveType) && null == nodeType) { // 10 虚拟表
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "TECH".equals(archiveType) && null == nodeType) { // TECH技术资料
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != nodeType && "1".equals(nodeType)) { // 节点类型 1 文件夹
					node.setIconCls("icon-im-newnmodulefile");
				} else if (null != nodeType && "2".equals(nodeType)) { // 数据节点
					node.setIconCls("icon-im-newndatanode");
				}
				node.setAttributes(row);
				BigDecimal childCount2 = BigDecimal.valueOf(Long.valueOf(row.get("CHILD_COUNT") + ""));
				if (null != childCount2 && childCount2.longValue() > 0) {
					if (level > 0) {
						node.setState("open");
					} else {
						node.setState("closed");
					}
					node.setChildren(recurFindTreeNodesByParentId(rid, orgId, deptId, level));
				} else {
					node.setState("open");
				}
				nodes.add(node);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nodes;
	}

	/**
	 * 获取子节点,对当前登陆用户的组织id和部门id进行过滤,只查询当前挡路用户组织和部门下的节点
	 * @param parentId
	 * @return 子节点集合
	 */
	public List<Map<String, Object>> findNodesByParentId(String parentId, String orgId, String deptId) throws Exception {
		Assert.notNull(parentId, "参数不能为空！");
		Object[] objs = new Object[2];
		objs[0] = orgId;
		objs[1] = parentId;
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("WITH T1 AS\n");
		sbSql.append(" (SELECT LAC.*\n");
		sbSql.append(" FROM LANTOP_ARCHIVE_CLASS LAC\n");
		sbSql.append(" CONNECT BY PRIOR LAC.ID = LAC.PARENT_ID\n");
		sbSql.append(" START WITH LAC.PARENT_ID = 'ROOT'),\n");
		sbSql.append("T2 AS\n");
		sbSql.append(" (SELECT *\n");
		sbSql.append(" FROM LANTOP_ARCHIVE_CLASS LAC1\n");
		sbSql.append(" WHERE LAC1.ARCHIVE_TYPE <> '0'\n"); //LAC1.ARCHIVE_TYPE <> '1'\n");
		sbSql.append(" AND LAC1.ORG_ID = '"+ orgId +"'\n");
		sbSql.append(" AND LAC1.ARCHIVE_TYPE <> '10'),\n");
		sbSql.append("T3 AS\n");
		sbSql.append(" (SELECT T1.*\n");
		sbSql.append(" FROM T1, T2\n");
		sbSql.append(" WHERE (INSTR(T2.ARCHIVE_CLASS_NODE_PATH, T1.ARCHIVE_CLASS_NODE_PATH) > 0\n");
		sbSql.append(" AND T1.ARCHIVE_TYPE = '0') OR T1.PARENT_ID = 'ROOT'),\n");
		sbSql.append("T4 AS\n");
		sbSql.append(" (SELECT T1.*\n");
		sbSql.append(" FROM T1, T2\n");
		sbSql.append(" WHERE INSTR(T1.ARCHIVE_CLASS_NODE_PATH, T2.ARCHIVE_CLASS_NODE_PATH) > 0),\n");
		sbSql.append("T AS\n");
		sbSql.append(" (SELECT DISTINCT T3.*\n");
		sbSql.append(" FROM T3\n");
		sbSql.append(" UNION ALL\n");
		sbSql.append(" SELECT T4.* FROM T4)\n");
		sbSql.append(" SELECT /*+CNNTB_OPT_FLAG(2) lkup_cpu(1) */ (SELECT COUNT(*)\n");
		sbSql.append("  FROM T A1\n");
		sbSql.append("  WHERE A1.PARENT_ID = A2.ID\n");
		sbSql.append("  AND A2.ARCHIVE_CLASS_NODE_CODE <> 'LANTOP_PUB_FIELD' AND ARCHIVE_CLASS_NODE_CODE <> 'GRWJ' AND ARCHIVE_CLASS_NODE_CODE <> 'BMWJ') AS CHILD_COUNT,\n");
		sbSql.append("  A2.*\n");
		sbSql.append(" FROM T A2\n");
		sbSql.append(" WHERE A2.ORG_ID = ?\n");
		sbSql.append(" AND A2.PARENT_ID = ? AND ARCHIVE_CLASS_NODE_CODE <> 'GRWJ' AND ARCHIVE_CLASS_NODE_CODE <> 'BMWJ'\n");
		sbSql.append(" ORDER BY A2.NODE_SORT_NUMBER ASC, A2.CREATION_DATE ASC\n");
		return this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString(), objs);
	}

	/**
	 * 根据树节点id获得对应数据
	 * @param id
	 * @return 实体对象
	 */
	public LantopArchiveClass getArchiveclassmanagerById(String id) throws Exception {
		LantopArchiveClass lantopArchiveClass = (LantopArchiveClass) hibernateDao.getSession().get(LantopArchiveClass.class, id);
		return lantopArchiveClass;
	}

	/**
	 * 根据节点id获得当前节点下最大节点排序值
	 */
	public int getMaxNodeSortNumber(String id) throws Exception {
		String sql = "SELECT MAX(LAC.NODE_SORT_NUMBER) FROM (SELECT (SELECT COUNT(*) FROM LANTOP_ARCHIVE_CLASS LAC2 WHERE LAC2.PARENT_ID = LAC1.ID) CHILD_COUNT, LAC1.* FROM LANTOP_ARCHIVE_CLASS LAC1 WHERE LAC1.PARENT_ID = ?) LAC";
		int number = this.jdbcAvicit.getJdbcTemplate().queryForInt(sql, id);
		return number;
	}

	/**
	 * 添加树节点
	 */
	public void saveTree(LantopArchiveClass lac) throws Exception {
		PojoUtil.setSysProperties(lac, OpType.insert);
		this.hibernateDao.save(lac);
		SysLogUtil.log(lac, null, OpType.insert, OpResult.success);
	}

	/**
	 * 删除节点,并删除节点下的子节点
	 */
	public void delTree(String id, String orgId, String deptId, String sysId) throws Exception {
		List<LantopArchiveClass> lacList = this.getNodeByParentId(id);
		if (lacList.size() > 0) {
			for (LantopArchiveClass lac : lacList) {
				if (lac.getArchiveClassNodeType().equals("2")) { // 数据节点
					this.commTableManagerIntfsService.deleteCbbTabNodeByNodeIdByIntfs(orgId, deptId, sysId, lac.getId());
				}
				this.delTree(lac.getId(), orgId, deptId, sysId);
			}
		}
		this.deleteTreeNodeById(id, orgId, deptId, sysId);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("nodeId", id);
		// 删除节点配置的权限数据
		userAuthIntfsService.deleteAuthByNodeIdByIntfs(orgId, deptId, sysId, param);
	}

	/**
	 * 获得节点下的子节点
	 * @author 钟一华
	 * @return List<LantopArchiveClass>
	 * @throws
	 */
	@Override
	public List<LantopArchiveClass> getNodeByParentId(String parentId) throws Exception {
		Assert.notNull(parentId);
		return this.hibernateDao.find("from LantopArchiveClass where parentId = ?", parentId);
	}

	/**
	 * 通过id删除节点
	 * @author 钟一华
	 * @param id void
	 * @throws
	 */
	public void deleteTreeNodeById(String id, String orgId, String deptId, String sysId) throws Exception {
		String findSql = "select * from lantop_archive_class where id = ?";
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(findSql, id);
		if (list.size() > 0) {
			Map<String, Object> map = list.get(0);
			String type = map.get("ARCHIVE_CLASS_NODE_TYPE").toString();
			if (type.equals("2")) {
				this.commTableManagerIntfsService.deleteCbbTabNodeByNodeIdByIntfs(orgId, deptId, sysId, id);
			}
		}
		String sql = "delete from lantop_archive_class where id = ?";
		this.jdbcAvicit.getJdbcTemplate().update(sql, id);
		SysLogUtil.log("档案分类树管理模块", "删除档案分类记录", OpType.delete, OpResult.success, LogBaseFactory.getLogBase());
	}

	/**
	 * 复制树节点和节点的子节点
	 */
	public void saveCopyTreeData(String parentId, String copyId, String orgId, String deptId, String sysId, String loginUserId, String loginIp) throws Exception {
		// 目标节点
		LantopArchiveClass lacP = this.hibernateDao.get(LantopArchiveClass.class, parentId);
		// 被复制节点
		LantopArchiveClass lac = this.getArchiveclassmanagerById(copyId);
		this.hibernateDao.evict(lac);
		String id = ComUtil.getId();
		lac.setId(id);
		lac.setParentId(parentId);
		lac.setArchiveClassNodePath(lacP.getArchiveClassNodePath() + "/" + lac.getId());
		boolean isRepeat = this.isRepeatNode(copyId, parentId);
		if (isRepeat) {
			String name = this.getClassNameByParentIdAndClassName(parentId, lac.getArchiveClassNodeName() + "-副本");
			lac.setArchiveClassNodeName(name);
			lac.setArchiveClassNodeCode(Pinyin4jUtil.getPinYinHeadChar(name));
		}
		// 如果节点类型是 数据节点,则执行下面操作
		if (null != lac.getArchiveClassNodeType()) {
			if (lac.getArchiveClassNodeType().equals("2")) {
				List<LantopArchiveClass> modelList = this.getModelData(lac.getParentId());
				LantopArchiveClass m = modelList.get(0);
				String modelId = m.getId();
				List<Map<String, Object>> tableIdsList = this.commTableManagerIntfsService.getCbbTableIdsByNodeIdByIntfs(orgId, deptId, sysId, modelId);
				for (int i = 0; i < tableIdsList.size(); i++) {
					Map<String, Object> tableMap = tableIdsList.get(i);
					String tableId = (String) tableMap.get("TABLE_ID");
					String tabFlag = (String) tableMap.get("TAB_FLAG");
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("TAB_FLAG", tabFlag);
					this.commTableManagerIntfsService.createCbbTabNodeByIntfs(orgId, deptId, sysId, id, tableId, loginUserId, loginIp, param);
				}
			}
		}
		this.hibernateDao.save(lac);
		SysLogUtil.log(lac, null, OpType.insert, OpResult.success);
		this.saveCopyTreeChildData(id, copyId, orgId, deptId, sysId, loginUserId, loginIp);
	}

	/**
	 * 复制节点数据
	 * @author 钟一华 
	 * @param parentId
	 * @param copyId void
	 * @throws
	 */
	public void saveCopyTreeChildData(String parentId, String copyId, String orgId, String deptId, String sysId, String loginUserId, String loginIp) throws Exception {
		LantopArchiveClass lacP = this.hibernateDao.get(LantopArchiveClass.class, parentId);
		List<LantopArchiveClass> lacList = this.hibernateDao.find("from LantopArchiveClass where parentId = ?", copyId);
		for (int i = 0; i < lacList.size(); i++) {
			LantopArchiveClass l = lacList.get(i);
			this.hibernateDao.evict(l);
			// 获得需要复制的id
			String clId = l.getId();
			// 新id
			String lId = ComUtil.getId();
			l.setId(lId);
			l.setParentId(parentId);
			l.setArchiveClassNodePath(lacP.getArchiveClassNodePath() + "/" + l.getId());
			// 如果节点类型是 数据节点,则执行下面操作
			if (l.getArchiveClassNodeType().equals("2")) {
				List<LantopArchiveClass> modelList = this.getModelData(l.getParentId());
				LantopArchiveClass m = modelList.get(0);
				String modelId = m.getId();
				List<Map<String, Object>> tableIdsList = this.commTableManagerIntfsService.getCbbTableIdsByNodeIdByIntfs(orgId, deptId, sysId, modelId);
				for (int j = 0; j < tableIdsList.size(); j++) {
					Map<String, Object> tableMap = tableIdsList.get(j);
					String tableId = (String) tableMap.get("TABLE_ID");
					String tabFlag = (String) tableMap.get("TAB_FLAG");
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("TAB_FLAG", tabFlag);
					this.commTableManagerIntfsService.createCbbTabNodeByIntfs(orgId, deptId, sysId, lId, tableId, loginUserId, loginIp, param);
				}
			}
			this.hibernateDao.save(l);
			SysLogUtil.log(l, null, OpType.insert, OpResult.success);
			this.saveCopyTreeChildData(lId, clId, orgId, deptId, sysId, loginUserId, loginIp);
		}
	}

	/**
	 * 获得节点路径
	 * @author 钟一华 
	 * @param pId
	 * @return String
	 * @throws
	 */
	public String getNodePathByParentId(String pId) throws Exception {
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("select sys_connect_by_path(a.id, '/') as archive_class_node_name_path,a.*\n");
		sbSql.append("from (select lac.id,\n");
		sbSql.append("lac.parent_id,\n");
		sbSql.append("lac.archive_class_node_code,\n");
		sbSql.append("lac.archive_class_node_name,\n");
		sbSql.append("lac.archive_type,\n");
		sbSql.append("lac.archive_class_node_type,\n");
		sbSql.append("lac.archive_class_node_path\n");
		sbSql.append("from lantop_archive_class lac) a\n");
		sbSql.append("WHERE a.id = ?\n");
		sbSql.append("connect by prior a.id = a.parent_id\n");
		sbSql.append("start with a.parent_id = 'ROOT'");
		List<Object[]> list = this.hibernateDao.findBySQL(sbSql.toString(), pId);
		Object[] objs = (Object[]) list.get(0);
		String path = objs[0].toString();
		return path;
	}

	/**
	 * 通过path拿到pathName及仅部门可见设置
	 * @author 钟一华
	 * @param path
	 * @return Map<String,Object>
	 * @throws
	 */
	public Map<String,Object> getPathNameByPath(String path) throws Exception {
		Map<String,Object> map = new HashMap<String,Object>();
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("SELECT T.ARCHIVE_CLASS_PATH_NAME,T.ATTRIBUTE_01\n");
		sbSql.append("FROM (SELECT A.ARCHIVE_CLASS_NODE_PATH,\n");
		sbSql.append("SYS_CONNECT_BY_PATH(A.ARCHIVE_CLASS_NODE_NAME, 'Ψ') AS ARCHIVE_CLASS_PATH_NAME ");
		sbSql.append(",A.ATTRIBUTE_01 \n");
		sbSql.append("FROM LANTOP_ARCHIVE_CLASS A\n");
		sbSql.append("START WITH A.PARENT_ID = 'ROOT'\n");
		sbSql.append("CONNECT BY PRIOR A.ID = A.PARENT_ID) T\n");
		sbSql.append("WHERE T.ARCHIVE_CLASS_NODE_PATH =\n");
		sbSql.append("'" + path + "'");
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
		if (list.size() > 0) {
			map = list.get(0);
			String pathName = map.get("ARCHIVE_CLASS_PATH_NAME").toString();
			pathName = pathName.replaceAll("Ψ", "/");
			map.put("ARCHIVE_CLASS_PATH_NAME", pathName);
		}
		return map;
	}

	/**
	 * 通过path拿到pathName检索模块使用
	 */
	public String getPathNameByPathForSearch(String path) throws Exception {
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("SELECT T.ARCHIVE_CLASS_PATH_NAME\n");
		sbSql.append("FROM (SELECT A.ARCHIVE_CLASS_NODE_PATH,\n");
		sbSql.append("SYS_CONNECT_BY_PATH(A.ARCHIVE_CLASS_NODE_NAME, 'Ψ') AS ARCHIVE_CLASS_PATH_NAME\n");
		sbSql.append("FROM LANTOP_ARCHIVE_CLASS A\n");
		sbSql.append("START WITH A.PARENT_ID = 'ROOT'\n");
		sbSql.append("CONNECT BY PRIOR A.ID = A.PARENT_ID) T\n");
		sbSql.append("WHERE T.ARCHIVE_CLASS_NODE_PATH =\n");
		sbSql.append("'" + path + "'");
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
		if (list.size() > 0) {
			Map<String, Object> map = list.get(0);
			String pathName = map.get("ARCHIVE_CLASS_PATH_NAME").toString();
			pathName = pathName.replaceAll("Ψ", "/");
			// 截取掉全宗
			pathName = pathName.substring(1);
			pathName = pathName.substring(pathName.indexOf("/") + 1);
			pathName = pathName.replace("/", "\\");
			return pathName;
		}
		return null;
	}

	/**
	 * 根据nodeId获取模版文件夹名称
	 * @author 郭亮
	 * @param nodeId
	 * @return
	 * @throws Exception String
	 */
	@Override
	public String getModelFileNameByNodeId(String nodeId) throws Exception {
		String pathName = "";//路径名称
		LantopArchiveClass lac = getArchiveclassmanagerById(nodeId); // 数据节点
		StringBuffer sbSql = new StringBuffer();
		List<String> list = new ArrayList<String>();
		if (lac != null) {
			sbSql.append("SELECT T.ARCHIVE_CLASS_NODE_NAME\n");
			sbSql.append(" FROM LANTOP_ARCHIVE_CLASS T\n");
			sbSql.append(" WHERE INSTR('" + lac.getArchiveClassNodePath() + "',T.ARCHIVE_CLASS_NODE_PATH) > 0\n");
			sbSql.append(" AND (T.ARCHIVE_TYPE = '0' OR T.ARCHIVE_TYPE = '1' OR T.ARCHIVE_TYPE = '2' OR");
			sbSql.append(" T.ARCHIVE_TYPE = '3' OR T.ARCHIVE_TYPE = '4' OR");
			sbSql.append(" T.ARCHIVE_TYPE = '5' OR T.ARCHIVE_TYPE = '6' OR");
			sbSql.append(" T.ARCHIVE_TYPE = '7' OR T.ARCHIVE_TYPE = '8' OR");
			sbSql.append(" T.ARCHIVE_TYPE = '9' OR T.ARCHIVE_CLASS_NODE_TYPE = '1' OR T.ARCHIVE_CLASS_NODE_TYPE = '2')");
			list = this.hibernateDao.findBySQL(sbSql.toString());
		}
		for (int i = 0; i < list.size(); i++) {
			if(i == 0){
				pathName = list.get(i);
			}else{
				pathName = pathName +  "\\" + list.get(i);
			}
		}
		return pathName;
	}

	/**
	 * 获得向上节点模板数据
	 */
	public List<LantopArchiveClass> getModelData(String id) throws Exception {
		// String sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS L WHERE L.ID = ? AND (L.ARCHIVE_TYPE != '0' AND L.ARCHIVE_TYPE IS NOT NULL)";
		String hql = "from LantopArchiveClass where id = ? and (archiveType != '0' and archiveType is not null)";
		List<LantopArchiveClass> lacs = this.hibernateDao.find(hql, new Object[] {id});
		// List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql, id);
		if (lacs.size() < 1) {
			// String findSql = "SELECT * FROM LANTOP_ARCHIVE_CLASS L WHERE ID = ?";
			LantopArchiveClass lac = this.hibernateDao.get(LantopArchiveClass.class, id);
			// List<Map<String, Object>> l = this.jdbcAvicit.getJdbcTemplate().queryForList(findSql, id);
			// Map<String, Object> m = l.get(0);
			String pid = lac.getParentId();
			return this.getModelData(pid);
		} else {
			return lacs;
		}
	}

	/**
	 * 判断新建节点名称是否已存在
	 */
	public boolean checkNodeNameByIntfs(String parentId, String nodeName) throws Exception {
		String sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS WHERE PARENT_ID = '" + parentId + "' AND ARCHIVE_CLASS_NODE_NAME = '" + nodeName + "'";
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		if (list.size() > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 判断节点名称是否存在
	 * @param parentId
	 * @param nodeName
	 * @param id
	 * @return
	 * @throws Exception 
	 * @throws
	 */
	public boolean checkNodeNameByIdByIntfs(String parentId, String nodeName, String id) throws Exception {
		String sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS WHERE PARENT_ID = '" + parentId + "' AND ARCHIVE_CLASS_NODE_NAME = '" + nodeName + "' AND ID != '" + id + "'";
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		if (list.size() > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 判断目标节点是否存在重复数据
	 */
	public boolean isRepeatNode(String copyId, String parentId) throws Exception {
		LantopArchiveClass lac = this.hibernateDao.get(LantopArchiveClass.class, copyId);
		String hql = "from LantopArchiveClass where parentId = ? and archiveClassNodeCode = ? and archiveClassNodeName = ?";
		List<LantopArchiveClass> list = this.hibernateDao.find(hql, new Object[] {parentId, lac.getArchiveClassNodeCode(), lac.getArchiveClassNodeName()});
		if (list.size() > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 更新节点数据
	 */
	public void updateData(String id, String sortNo, String className, String remark, String attribute01) throws Exception {
		LantopArchiveClass lac = this.hibernateDao.get(LantopArchiveClass.class, id);
		this.hibernateDao.evict(lac);
		LantopArchiveClass temp = new LantopArchiveClass();
		PojoUtil.copyProperties(temp, lac, true);
		if (null != className && !"".equals(className)) {
			temp.setArchiveClassNodeName(className);
		}
		temp.setAttribute01(attribute01);
		temp.setRemark(remark);
		if (null != sortNo || !"".equals(sortNo)) {
			BigDecimal no = BigDecimal.valueOf(Long.parseLong(sortNo));
			temp.setNodeSortNumber(no);
		}
		// 记录日志
		SysLogUtil.log(temp, lac, OpType.update, OpResult.success);
		PojoUtil.setSysProperties(temp, OpType.update);
		this.hibernateDao.update(temp);
	}

	/**
	 * 通过id更新节点名称和路径
	 * @param id
	 * @param nodeName
	 * @param parentPath
	 * @throws Exception 
	 * @throws
	 */
	public void updateTreeNodeData(String id, String nodeName, String parentPath) throws Exception {
		LantopArchiveClass lac = this.hibernateDao.get(LantopArchiveClass.class, id);
		this.hibernateDao.evict(lac);
		LantopArchiveClass temp = new LantopArchiveClass();
		PojoUtil.copyProperties(temp, lac, true);
		temp.setArchiveClassNodeName(nodeName);
		temp.setArchiveClassNodeCode(Pinyin4jUtil.getPinYinHeadChar(nodeName));
		temp.setArchiveClassNodePath(parentPath + "/" + id);
		// 记录日志
		SysLogUtil.log(temp, lac, OpType.update, OpResult.success);
		PojoUtil.setSysProperties(temp, OpType.update);
		this.hibernateDao.update(temp);
	}

	/**
	 * 获得所有节点数据集合
	 */
	public List<Map<String, Object>> getArchiveClassList() {
		String sql = "select * from lantop_archive_class";
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		return list;
	}

	/**
	 * 通过父ID获得子节点数据
	 */
	public Paging<LantopArchiveClass> getTreeDataByParentId(Paging<LantopArchiveClass> page, String parentId) throws Exception {
		String hql = "from LantopArchiveClass where parentId = '" + parentId + "' and archiveClassNodeCode not in ('BMWJ', 'GRWJ') order by nodeSortNumber asc, creationDate asc";
		Paging<LantopArchiveClass> paging = this.hibernateDao.findPage(page, hql);
		return paging;
	}

	/**
	 * 获取复制后节点名称
	 * @param parentId
	 * @param className
	 * @return
	 * @throws Exception String
	 * @throws
	 */
	public String getClassNameByParentIdAndClassName(String parentId, String className) throws Exception {
		String sql = "select * from lantop_archive_class where parent_id = '" + parentId + "' and archive_class_node_name like '" + className + "%'";
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		String newName = "";
		if (list.size() > 0) {
			StringBuffer sbSql = new StringBuffer();
			sbSql.append("SELECT MAX(MAXNUM) MAXNUM FROM (SELECT SUBSTR(SUBSTR(T.ARCHIVE_CLASS_NODE_NAME, 0, LENGTH('" + className + "')+2), LENGTH('" + className
					+ "')+2) AS MAXNUM \n");
			sbSql.append("FROM LANTOP_ARCHIVE_CLASS T\n");
			sbSql.append("WHERE T.ARCHIVE_CLASS_NODE_NAME LIKE '" + className + "%') A\n");
			sbSql.append("WHERE REGEXP_LIKE(A.MAXNUM, '(^[+-]?\\d{0,}\\.?\\d{0,}$)')");
			List<Map<String, Object>> maxNumList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
			if (maxNumList.size() > 0) {
				Map<String, Object> map = maxNumList.get(0);
				String maxnum = (String) map.get("MAXNUM");
				if (null != maxnum) {
					Pattern pattern = Pattern.compile("[0-9]*");
					Matcher isNum = pattern.matcher(maxnum);
					if (!isNum.matches()) {
						newName = className + "(1)";
					} else {
						int max = Integer.valueOf(maxnum) + 1;
						newName = className + "(" + max + ")";
					}
				} else {
					newName = className + "(1)";
				}
			}
		} else {
			newName = className;
		}
		return newName;
	}

	/**
	 * 通过查询条件,返回查询到的节点路径集合
	 */
	public List<String> getNodePathsByNodeName(String nodeName) throws Exception {
		List<String> pathList = new ArrayList<String>();
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("SELECT ARCHIVE_CLASS_NODE_PATH FROM (SELECT * FROM (SELECT * FROM LANTOP_ARCHIVE_CLASS\n");
		sbSql.append("WHERE ARCHIVE_CLASS_NODE_CODE NOT IN ('GRWJ', 'BMWJ')) T\n");
		sbSql.append("CONNECT BY PRIOR T.ID = T.PARENT_ID START WITH T.PARENT_ID = 'ROOT') A\n");
		sbSql.append("WHERE UPPER(A.ARCHIVE_CLASS_NODE_NAME) LIKE UPPER('%" + nodeName + "%')");
		// String sql = "SELECT ARCHIVE_CLASS_NODE_PATH FROM LANTOP_ARCHIVE_CLASS WHERE ARCHIVE_CLASS_NODE_NAME LIKE '%" + nodeName + "%'";
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			pathList.add((String) map.get("ARCHIVE_CLASS_NODE_PATH"));
		}
		return pathList;
	}

	/**
	 * 获得树形数据
	 */
	public List<TreeNode> findSearchTreeNode(String orgId, String deptId, String id, List<String> paths, String value) throws Exception {
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		// 查询业务数据
		List<Map<String, Object>> childTreeList = findNodesByParentIdAndPaths(orgId, deptId, id, paths, value);
		try {
			// 将业务数据格式转换成esayui树形格式，此处封装了一个TreeNodeVo节点
			for (Map<String, Object> row : childTreeList) {
				String rid = (String) row.get("id");
				String rname = (String) row.get("archive_class_node_name");
				String archiveType = (String) row.get("ARCHIVE_TYPE");
				String nodeType = (String) row.get("ARCHIVE_CLASS_NODE_TYPE");
				String parentId = (String) row.get("PARENT_ID");
				TreeNode node = new TreeNode();
				node.setId(rid);
				node.setText(rname);
				// 根据节点类型,设置节点图标
				if (null != parentId && "ROOT".equals(parentId)) { // 根节点
					node.setIconCls("icon-im-newnorg");
				} else if (null != archiveType && "-1".equals(archiveType) && null == nodeType) { // 档案类型 -1 物理表
					node.setIconCls("icon-im-newntable");
				} else if (null != archiveType && "0".equals(archiveType) && null == nodeType) { // 0 模版文件夹
					node.setIconCls("icon-im-newnmodulefile");
				} else if (null != archiveType && "1".equals(archiveType) && null == nodeType) { // 1 标识文件
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "2".equals(archiveType) && null == nodeType) { // 2 档案
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "3".equals(archiveType) && null == nodeType) { // 3 专题库
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "4".equals(archiveType) && null == nodeType) { // 4 多媒体
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "5".equals(archiveType) && null == nodeType) { // 5 项目归档计划
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "6".equals(archiveType) && null == nodeType) { // 6 管务
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "7".equals(archiveType) && null == nodeType) { // 7 其他
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "8".equals(archiveType) && null == nodeType) { // 8 资料
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "9".equals(archiveType) && null == nodeType) { // 9 图书
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "10".equals(archiveType) && null == nodeType) { // 10 虚拟表
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != archiveType && "TECH".equals(archiveType) && null == nodeType) { // TECH技术资料
					node.setIconCls("icon-im-newnmodulelib");
				} else if (null != nodeType && "1".equals(nodeType)) { // 节点类型 1 文件夹
					node.setIconCls("icon-im-newnmodulefile");
				} else if (null != nodeType && "2".equals(nodeType)) { // 数据节点
					node.setIconCls("icon-im-newndatanode");
				}
				node.setAttributes(row);
				BigDecimal childCount2 = BigDecimal.valueOf(Long.valueOf(row.get("CHILD_COUNT") + ""));
				if (null != childCount2 && childCount2.longValue() > 0) {
					List<TreeNode> cnodes = findSearchTreeNode(orgId, deptId, rid, paths, value);
					node.getChildren().addAll(cnodes);
					node.setState("open");
				} else {
					node.setState("open");
				}
				nodes.add(node);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nodes;
	}

	/**
	 * 树查询方法,查询树结构数据
	 * @author 钟一华
	 * @param orgId
	 * @param deptId
	 * @param parentId
	 * @param paths
	 * @param value
	 * @return
	 * @throws Exception List<Map<String,Object>>
	 * @throws
	 */
	public List<Map<String, Object>> findNodesByParentIdAndPaths(String orgId, String deptId, String parentId, List<String> paths, String value) throws Exception {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if (null != value && !"".equals(value) && paths.size() > 0) {
			StringBuffer sbSql = new StringBuffer();
			sbSql.append("WITH TREE AS (SELECT * FROM (SELECT T.*\n");
			sbSql.append("FROM LANTOP_ARCHIVE_CLASS T WHERE \n");
			for (int i = 0; i < paths.size(); i++) {
				sbSql.append("INSTR('" + paths.get(i) + "', T.ARCHIVE_CLASS_NODE_PATH) > 0\n");
				if (i != paths.size() - 1) {
					sbSql.append(" OR ");
				}
			}
			sbSql.append(")) SELECT (SELECT COUNT(*) FROM TREE TR2\n");
			sbSql.append("WHERE TR2.PARENT_ID = TR1.ID AND TR2.ORG_ID = '" + orgId + "') CHILD_COUNT, TR1.*\n");
			sbSql.append("FROM TREE TR1\n");
			sbSql.append("WHERE TR1.PARENT_ID = '" + parentId + "'\n");
			sbSql.append("AND ARCHIVE_CLASS_NODE_CODE NOT IN ('BMWJ', 'GRWJ')\n");
			sbSql.append("ORDER BY TR1.NODE_SORT_NUMBER ASC, TR1.CREATION_DATE ASC");
			list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
		} else if ("".equals(value)) {
			Assert.notNull(parentId, "参数不能为空！");
			Object[] objs = new Object[3];
			objs[0] = orgId;
			// objs[1] = deptId;
			objs[1] = parentId;
			objs[2] = orgId;
			String sql = "SELECT (SELECT COUNT(*) FROM LANTOP_ARCHIVE_CLASS LAC2 WHERE LAC2.PARENT_ID=LAC1.ID AND LAC2.ORG_ID = ?) CHILD_COUNT,LAC1.* FROM LANTOP_ARCHIVE_CLASS LAC1 WHERE LAC1.PARENT_ID=? AND LAC1.ORG_ID = ? AND ARCHIVE_CLASS_NODE_CODE NOT IN ('BMWJ','GRWJ') ORDER BY LAC1.NODE_SORT_NUMBER ASC, LAC1.CREATION_DATE ASC";
			list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql, objs);
		}
		return list;
	}

	/**
	 * 文件类型根据数据节点ID获取tabNodeId（就是‘个人文件’或者‘部门文件’的节点ID）
	 * @author 郭亮
	 * @param nodeId 节点ID
	 * @return
	 * @throws Exception String
	 */
	@Override
	public String getFileTabNodeIdByNodeId(String nodeId) throws Exception {
		String tabNodeId = "";
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("WITH T1 AS\n");
		sbSql.append(" (SELECT LAC.ID,\n");
		sbSql.append(" LAC.PARENT_ID,\n");
		sbSql.append(" LAC.ARCHIVE_CLASS_NODE_CODE,\n");
		sbSql.append(" LAC.ARCHIVE_CLASS_NODE_PATH AS PH\n");
		sbSql.append(" FROM LANTOP_ARCHIVE_CLASS LAC\n");
		sbSql.append(" CONNECT BY PRIOR LAC.ID = LAC.PARENT_ID\n");
		sbSql.append(" START WITH LAC.PARENT_ID = 'ROOT'),\n");
		sbSql.append(" T2 AS\n");
		sbSql.append(" ( \n");
		sbSql.append(" SELECT T1.PH FROM T1\n");
		sbSql.append(" WHERE T1.ID = '" + nodeId + "'\n");
		sbSql.append(" ),\n");
		sbSql.append(" T3 AS\n");
		sbSql.append(" (\n");
		sbSql.append(" SELECT T1.*\n");
		sbSql.append(" FROM T2, T1\n");
		sbSql.append(" WHERE INSTR(T2.PH, T1.PH) > 0\n");
		sbSql.append(" AND (T1.ARCHIVE_CLASS_NODE_CODE = 'GRWJ' OR T1.ARCHIVE_CLASS_NODE_CODE = 'BMWJ')\n");
		sbSql.append(" )\n");
		sbSql.append(" SELECT T3.ID FROM T3");
		List<String> list = this.hibernateDao.findBySQL(sbSql.toString());
		if (list.size() > 0) {
			tabNodeId = list.get(0);
		}
		return tabNodeId;
	}
	
	/**
	 * 根据数据节点nodeId获取ModelNodeId（模板文件夹NODE_ID）
	 * @param nodeId
	 * @return
	 * @throws Exception String
	 * @throws
	 */
	@Override
	public String getFileModelNodeIdByNodeId(String nodeId) throws Exception {
		String modelNodeId = "";
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("WITH T1 AS\n");
		sbSql.append(" (SELECT LAC.ID,\n");
		sbSql.append("         LAC.PARENT_ID,\n");
		sbSql.append("         LAC.ARCHIVE_TYPE,\n");
		sbSql.append("         LAC.ARCHIVE_CLASS_NODE_PATH AS PH\n");
		sbSql.append("    FROM LANTOP_ARCHIVE_CLASS LAC\n");
		sbSql.append("  CONNECT BY PRIOR LAC.ID = LAC.PARENT_ID\n");
		sbSql.append("   START WITH LAC.PARENT_ID = 'ROOT'),\n");
		sbSql.append("T2 AS\n");
		sbSql.append(" (SELECT T1.PH FROM T1 WHERE T1.ID = '"+ nodeId +"'),\n");
		sbSql.append("\n");
		sbSql.append("T3 AS\n");
		sbSql.append(" (SELECT T1.*\n");
		sbSql.append("    FROM T2, T1\n");
		sbSql.append("   WHERE INSTR(T2.PH, T1.PH) > 0\n");
		sbSql.append("     AND (T1.ARCHIVE_TYPE IN\n");
		sbSql.append("          ('1', '2', '3', '4', '5', '6', '8', '9', 'TECH')))\n");
		sbSql.append("SELECT T3.ID FROM T3"); 
		List<String> list = this.hibernateDao.findBySQL(sbSql.toString());
		if (list.size() > 0) {
			modelNodeId = list.get(0);
		}
		return modelNodeId;
	}

	@Override
	public List<TreeNode> getArchiveClassTreeNodeToDataNodeInfoByIntfsBatchPrint(
			String orgId, String deptId, String sysId, String archiveType,
			Map<String, Object> params) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	/**
	 * 根据节点ID获取节点信息
	 * @param nodeId
	 * @return
	 * @throws Exception List<Map<String,Object>>
	 * @throws
	 */
	@Override
	public List<Map<String,Object>> getArchiveClassTreeNodeByNodeId(String nodeId) throws Exception {
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("SELECT *\n");
		sbSql.append("  FROM LANTOP_ARCHIVE_CLASS T\n");
		sbSql.append(" WHERE T.ID = '" + nodeId + "'"); 
		List<Map<String, Object>> list = jdbcAvicit.queryForMap(sbSql.toString(), null);
		return list;
	}
	
	/**
	 * 通过节点集合返回数据节点信息
	 * @param nodeId
	 * @return
	 * @throws Exception Map<String,Object>
	 * @throws
	 */
	public Map<String, Object> getDataNodeInfoByParam(Map<String, Object> param) throws Exception {
		Map<String, Object> p = new HashMap<String, Object>();
		if (param.containsKey("treeNodeList")) {
			List<Map<String, Object>> treeNodeIdList = (List<Map<String, Object>>) param.get("treeNodeList");
			int dataCount = 0;
			for (int i = 0; i < treeNodeIdList.size(); i++) {
				Map<String, Object> mm = treeNodeIdList.get(i);
				Object tabFlag = mm.get("TAB_FLAG");
				if (null != tabFlag && !"".equals(tabFlag) && ("0".equals(tabFlag) || "1".equals(tabFlag))) {
					dataCount++;
				}
			}
			p.put("dataCount", dataCount);
		}
		if (param.containsKey("nodeId")) {
			String nodeId = (String) param.get("nodeId");
			Map<String, Object> modelMap = this.getModelFolderInfoByNodeId(nodeId);
			p.put("archiveType", modelMap.get("ARCHIVE_TYPE"));
		}
		return p;
	}
	
	/**
	 * 根据节点id获取模板文件夹信息
	 * @param nodeId
	 * @return
	 * @throws Exception Map<String,Object>
	 * @throws
	 */
	public Map<String, Object> getModelFolderInfoByNodeId(String nodeId) throws Exception {
		String sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS WHERE ID = '" + nodeId + "'";
		Map<String, Object> map = this.jdbcAvicit.getJdbcTemplate().queryForMap(sql);
		Object archiveType = map.get("ARCHIVE_TYPE");
		if (null != archiveType && !"".equals(archiveType) && !"0".equals(archiveType)) {
			return map;
		} else {
			String id = (String) map.get("PARENT_ID");
			return this.getModelFolderInfoByNodeId(id);
		}
	}
}
